<template>
  <div class="edit">
    <n-page-header @back="handleBack" :subtitle="subtitle">
      <template #extra>
        <n-space>
          <n-button type="info" @click="handleSave">保存</n-button>
        </n-space>
      </template>
    </n-page-header>
    <div class="edit_main">
      <div class="left">
        <h3 >商品信息</h3>
        <n-form label-placement="left" label-width="90px" :model="editForm?.product">
          <n-row :gutter="24">
            <n-col :span="22">
              <n-form-item label="商品名称">
                <n-input size="small" v-model:value="editForm.product.product_name"></n-input>
              </n-form-item>
            </n-col>
          </n-row>
          <n-row :gutter="24">
            <n-col :span="22">
              <n-form-item label="商品分类">
                <n-tree-select
                    :options="options"
                    placeholder="商品分类"
                    v-model:value="editForm.product.category_id"
                    :on-update:value="handleChange"
                    size="small"
                />
              </n-form-item>
            </n-col>
          </n-row>
          <n-row :gutter="24">
            <n-col :span="22">
              <n-form-item label="商品品牌">
                <n-select
                    placeholder="商品品牌"
                    v-model:value="editForm.product.brand_id"
                    size="small"
                    :options="brand_options"
                />
              </n-form-item>
            </n-col>
          </n-row>
          <n-row :gutter="24">
            <n-col :span="22">
              <n-form-item label="发货地址">
                <n-input size="small" placeholder="发货地址" v-model:value="editForm.product.product_address"/>
              </n-form-item>
            </n-col>
          </n-row>
          <n-row :gutter="24">
            <n-col :span="22">
              <n-form-item label="商品数量">
                <n-input-number style="width: 100%" size="small" placeholder="商品数量" v-model:value="editForm.product.product_count"/>
              </n-form-item>
            </n-col>
          </n-row>
          <n-row :gutter="24">
            <n-col :span="22">
              <n-form-item label="商品价格">
                <n-input-number style="width: 100%" size="small" placeholder="商品价格" v-model:value="editForm.product.product_money"/>
              </n-form-item>
            </n-col>
          </n-row>
          <n-row :gutter="24">
            <n-col :span="22">
              <n-form-item label="商品图片">
                <ImgUpload v-model:value="editForm.product.product_pic" url="ums/product/pic"></ImgUpload>
              </n-form-item>
            </n-col>
          </n-row>
        </n-form>
      </div>
      <div class="right">
        <n-tabs type="line" animated @update:value="beforLeave" v-model:value="tabValue">
          <n-tab-pane name="商品颜色">
            <EditColor ref="color"></EditColor>
          </n-tab-pane>
          <n-tab-pane name="商品图片">
            <div style="margin-bottom: 20px">
              <h4>轮播图</h4>
              <n-upload
                  list-type="image-card"
                  :headers="{token}"
                  :action="action"
                  :max="6"
                  v-model:file-list="editForm.fileList"
                  @before-upload="beforeUpload"
                  :on-remove="handleRemove"
                  :on-finish="handleFinish"
              ></n-upload>
            </div>
            <div>
              <h4>详情图片</h4>
              <n-upload
                  list-type="image-card"
                  :headers="{token}"
                  :action="action"
                  v-model:file-list="fileList"
                  @before-upload="beforeUpload"
                  :on-remove="handleRemove"
                  :on-finish="handleFinish"
              ></n-upload>
            </div>
          </n-tab-pane>
          <n-tab-pane name="商品详情">
            <div style="height: 100%">
              <div style="height: 60px">
                <n-button type="info" @click="handleAdd">添加</n-button>
              </div>
              <div style="height: calc(100% - 60px);overflow: hidden;padding-right: 20px;box-sizing: border-box;overflow-y: auto;">
                <n-data-table
                    v-model:data="tableList"
                    :columns="columns"
                />
              </div>
            </div>
          </n-tab-pane>
        </n-tabs>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
export default {
  name: "edit"
}
</script>

<script setup lang="ts">
import ImgUpload from '@/components/ImgUpload.vue'
import {useRoute, useRouter} from 'vue-router'
import {nextTick, onMounted, reactive, ref, h} from "vue"
import {
  sms_product_del,
  sms_product_queryList,
  ums_brand_queryList,
  ums_category_treeList,
  ums_product_update
} from '@/api/sms'
import {PicList, productListType} from '@/view/shopping/product/productType'
import {ModalFormOption, ModalFormTreeOption} from '@/type/ModalFormType'
import {treeNode} from '@/utils'
import EditColor from '@/view/shopping/product/EditColor.vue'
import {categoryListType} from '@/view/shopping/category/category'
import url from '@/static/config'
import {NInput, UploadFileInfo, NSpace, NButton} from 'naive-ui'
import useMsg from '@/hooks/useMsg'

const {success, error} = useMsg()
const token: string = sessionStorage.getItem('token')!
const action = url + "ums/product/pic"
const router = useRouter()
const route = useRoute()
const color = ref<{
  init: () => void
}>()
//
const tabValue = ref<"商品颜色" | "商品图片" | "商品详情">('商品颜色')

const subtitle = ref<string>('')
const fileList = ref<UploadFileInfo[]>([])
const editForm = reactive<{
  product: productListType
  fileList: UploadFileInfo[]
}>({
  product: {
    product_pic: '',
    product_name: '',
    category_id: '',
    brand_id: '',
    product_address: '',
    product_count: 0,
    product_money: 0.00,
    product_id: '',
    hot: '',
    category_name: '',
    brand_name: ''
  },
  fileList: []
})

const options = ref<ModalFormTreeOption[]>([])
const brand_options = ref<ModalFormOption[]>([])
const handleBack = () => {
  router.push("/shopping/product")
}

const list = ref<string[]>([])

function beforeUpload (data: {
  file: UploadFileInfo
  fileList: UploadFileInfo[]
}) {
  /*if (data.file.file?.type !== 'image/png' && data.file.file?.type !== 'image/jpeg') {
    error('只能上传png,jpg,jpeg格式的图片文件，请重新上传')
    return false
  }*/
  return true
}

function handleRemove (options: { file: UploadFileInfo, fileList: Array<UploadFileInfo> }): Promise<boolean> | boolean |any{
  const urls = options.file.url!.split("/")
  const url = urls[urls.length - 1]
  sms_product_del({url}).then(res => {
    if (res.code === 200) {
      success(res.message)
    } else {
      error(res.message)
    }
  })
}

const handleFinish = (options: {file: UploadFileInfo, event?: ProgressEvent}) => {
  const res = JSON.parse(options!.event?.target?.response as string)
  if (res.code === '200'){
    success(res.message)
    /*editForm.fileList.push({
      id: res.data,
      name: subtitle.value + String(editForm.fileList.length),
      status: "finished",
      url: res.data
    })*/

    options.file.url = url + 'static/product/' + res.data
    options.file.name = subtitle.value
    return options.file
  }
}
const columns = [
  {
    title: "参数名称",
    key: "label",
    titleAlign: "center",
    render: (r:PicList) => {
      return h(NInput, {
        value: r.label,
        placeholder: "请输入参数名称",
        onUpdateValue: (v) => {
          r.label = v
        }
      })
    }
  },
  {
    title: "参数值",
    key: 'value',
    titleAlign: "center",
    render: (r:PicList) => {
      return h(NInput, {
        value: r.value,
        placeholder: "请输入参数值",
        onUpdateValue: (v) => {
          r.value = v
        }
      })
    }
  },
  {
    title: "操作",
    key: 'value',
    titleAlign: "center",
    render: (r:PicList) => {
      return h("div", {
        style: {
          display: 'flex',
          justifyContent: 'center'
        }
      }, h(NButton, {
        type: "error",
        onClick: () => {
          tableList.value = tableList.value.filter(item => item.id !== r.id)
        }
      }, "删除"))
    }
  }
]
const tableList = ref<PicList[]>([])

const handleAdd = () => {
  const id = tableList.value.length ? tableList.value[tableList.value.length - 1].id : 0
  tableList.value.push({
    id: id + 1,
    product_id: route.query.product_id as string,
    label: '',
    value: ''
  })
}

// 保存
const handleSave = () => {
  console.log(editForm)
  console.log(tableList.value)
  const product:productListType = JSON.parse(JSON.stringify(editForm.product))
  delete product.brand_name
  delete product.category_name
  const picUrls = editForm.fileList.map(item => {
    const urls = item.url!.split("/")
    const picUrl = urls[urls.length - 1]
    return picUrl
  }).join(",")

  const infoPics = fileList.value.map(item => {
    const urls = item.url!.split("/")
    const picUrl = urls[urls.length - 1]
    return picUrl
  }).join(",")
  ums_product_update({
    product,
    infoList: tableList.value.map(item => ({
      label: item.label,
      value: item.value
    })),
    picUrls,
    infoPics
  }).then(res => {
    if (res.code === 200) {
      success(res.message)
      handleBack()
    } else {
      error(res.message)
    }
  }, err =>{
    error(err.toString())
  })
}

const beforLeave = (tabName: "商品颜色" | "商品图片" | "商品详情") => {
  nextTick(() => {
    switch (tabName) {
      case '商品图片':
        // console.log(1)
        break
      case '商品详情':
        // console.log(2)
        break
      case '商品颜色':
        color.value?.init()
        break
    }
  })

  tabValue.value = tabName
}

function brandList (v:string):Promise<void> {
  return ums_brand_queryList({
    category_id: v
  }).then(res => {
    if (res.code === 200) {
      if (res.data.length) {
        brand_options.value = res.data.map(item => ({
          label: item.brand_name,
          value: item.brand_id
        }))
      }
    }
    return
  })
}

const handleChange = (v) => {
  editForm.product.category_id = v
  brand_options.value = []
  editForm.product.brand_id = ''
  brandList(v)
}

onMounted( () => {
  ums_category_treeList().then(res => {
    options.value = res.data.map(item => treeNode<categoryListType>(item, {
      label: "category_name",
      key: "category_id"
    }))
  })
  sms_product_queryList({
    id: route.query.product_id as string
  }).then(res => {
    color.value?.init()
    console.log(color.value)
    brandList(res.data.product.category_id).then(() => {
      subtitle.value = res.data.product.product_name
      editForm!.product = res.data.product
      editForm.fileList = res.data.pics.map(item => ({
        name: item.product_pic_url,
        status: "finished",
        id: item.id.toString(),
        url: url + "static/product/" + item.product_pic_url
      }))
      fileList.value = res.data.infoPics.map(item => ({
        url: url + "static/product/" + item.pic,
        name: item.pic,
        status: "finished",
        id: item.id.toString(),
      }))
      tableList.value = res.data.productInfos
    })
  })
} )
</script>

<style scoped lang="scss">
.edit{
  height: 100%;
  &_main{
    height: calc(100% - 34px);
    overflow: hidden;
    overflow-y: auto;
    display: flex;
  }
  .left{
    width: 400px;
    border-right: 1px solid #ccc;
    height: 100%;
    margin-right: 10px;
    h3{
      margin: 8px 0;
    }
  }
  .right{
    flex: 1;
    h4{
      margin-bottom: 6px;
    }
    :deep(.n-tabs){
      height: 100%;
      .n-tabs-nav{
        height: 42px;
      }
      .n-tabs-pane-wrapper{
        height: calc(100% - 42px);
      }
      .n-tab-pane{
        height: calc(100% - 12px);
      }
    }
  }
}
</style>
